require(["jquery", "paging", "template", "bootstrap", "echarts", "bbcare", "scprit/department/view/template/follow-up/common.js"], function ($, Paging, template, bootstrap, echarts, $bb, $common) {

    var URL = $bb.baseUrl("department") + "followup/service"
    var obj = $bb.getPageParams()
    var userId = obj.babyId,
        type = obj.type //历史记录传参;
    var count = 1,
        pagesize = 16
    'use strict'
    var HashMap = $common.hashmap(),
        hashMap = new HashMap()

    var allPostion
    var months = [0.93, 1.87, 2.8, 3.73, 4.67, 5.6, 6.5, 7.5, 8.4, 9.3, 10.3, 11.2, 12.1, 13.1, 15, 18, 21, 24, 30, 36, 42, 48, 54, 60, 72]
    var weeks = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56] //13.1月
    getBabyInfo()
    getAllPostion()
    $common.date()
    $(".mask, .AddInformation").hide()
    $("#historyData").click(function (event) {
        getBabyList(1, pagesize)
        var p = new Paging()
        $("#pageTool").html("")
        p.init({
            target: '#pageTool',
            pagesize: pagesize,
            count: count,
            toolbar: false,
            callback: function (page, size, count) {
                getBabyList(page, size)
            }
        })
        $(".mask, .AddInformation").show()
    })
    $(".AddInformation h4 span").click(function (event) {
        $(".mask, .AddInformation").hide()
    })
    var account = eval('(' + sessionStorage.account + ')')
    var accountName = account.alias
    $("#userName").html(accountName) //检查医生名字
    $("#nowTime").html($common.getNowFormatDate())

    function getBabyInfo () {
        $bb.ajax({
            url: URL + "/patient/patientInfoPtId",
            data: JSON.stringify({
                data: {
                    "patientId": userId
                }
            }),
            success: function (data) {
                if (data.success) {
                    var babyInfo = data.data.PatientInfo
                    var babyData = $common.babyInfoDeal(babyInfo)
                    $common.infoInit({ "id": "#babyInfoList", "data": babyData })
                }
            }
        })
    }

    function getAllPostion () {
        $bb.ajax({
            url: URL + "/patient/evaluation/getAllPostion",
            async: false,
            data: JSON.stringify({
                data: {
                    "examinationPaperName": type, //评测类型；
                    "userId": userId
                }
            }),
            success: function (data) {
                if (data.success) {
                    allPostion = data.data
                    showPostion(allPostion, 1)
                }
            }
        })
    }
    if (window.__config__.role.indexOf('ReadOnly') > -1) {
        $('#submitData').css({
            display: 'none'
        })

    }
    $("#submitData").click(function () {

        if (!$.isEmptyObject(hashMap.map)) {
            $bb.ajax({
                url: URL + "/patient/evaluation/getScore",
                data: JSON.stringify({
                    data: {
                        "userId": userId,
                        "examinationPaperName": type,
                        "postionIds": JSON.stringify(hashMap)
                    }
                }),
                success: function (data) {
                    if (data.success) {
                        localStorage.setItem("GesellIntelligence", JSON.stringify(data.data))
                        $bb.openPage("gasellIntelligenceResult", obj)
                    }
                }
            })
        } else {
            $bb.toastShow("问卷还没有做，请做完之后再提交", 1500)
        }
    })
    $.tabs = {
        init: function () {
            this.orgData = months //s数据源
            this.showData = weeks
            this.showNumber = 8 //每组显示X条数据
            this.groupIndex = 0 //当前租索引
            this.initStyle()
        },
        bind: function () {
            var _this = this
            $(".tabs-ul li[group]").click(function () { //绑定分组的单击事件
                var group = $(this).attr("group")
                if (group == "prev") {
                    if (_this.groupIndex > 0) {
                        _this.groupIndex--
                        _this.initStyle()

                    }
                } else if (group == "next") {
                    var maxGroupIndex = _this.orgData.length / _this.showNumber
                    if (_this.orgData.length % _this.showNumber != 0) {
                        maxGroupIndex = parseInt(_this.orgData.length / _this.showNumber) + 1
                    }
                    maxGroupIndex--
                    if (_this.groupIndex < maxGroupIndex) {
                        _this.groupIndex++
                        _this.initStyle()

                    }
                }
            })
            $(".tabs-ul li[item]").click(function () {
                var index = parseInt($(this).attr("item"))
                $(".tabs-ul li[item]").removeClass("active")
                $(this).addClass("active")
                showPostion(allPostion, months[index])
            })
        },
        initStyle: function (itemIndex) {
            var _this = this,
                data = _this.orgData,
                showData = _this.showData,
                showNumber = _this.showNumber,
                count = data.length,
                groupIndex = _this.groupIndex,
                start = 0,
                end = 0,
                str = '<li group="prev"><a href="javascript:;">《</a></li>'
            start = groupIndex * showNumber
            end = (groupIndex + 1) * showNumber
            end > count ? (end = count) : ''
            for (var i = start; i < end; i++) {
                var cls = ' class='
                if (i == start || i == itemIndex) {
                    cls += '"active" '
                }
                var val
                if (String(data[i]).indexOf(".") != "-1") {
                    val = showData[i] + "周"
                } else {
                    val = data[i] + "月"
                }
                str += '<li item="' + i + '" ' + cls + '><a href="javascript:;">' + val + '</a><i></i></li>'
            }
            str += '<li group="next"><a href="javascript:;">》</a></li>'
            $(".tabs-ul").html(str)
            this.bind()
            showPostion(allPostion, months[start])
        },
        changeTabs: function (index) { }
    }
    $.tabs.init()

    function setResult () {
        var obj = $bb.getPageParams()
        if (obj.result) {
            var result = JSON.parse(obj.result)
            var resultMap = result["map"]
            var arr = []
            for (var item in resultMap) {
                var obj = {}
                obj.id = item
                obj.tab = resultMap[item]
                arr.push(obj)
            }
            for (var i = 0; i < arr.length; i++) {
                var $this = $('div#' + arr[i].id + '.td-chd')
                $this.unbind('click')
                $("div#" + arr[i].id + ".td-chd li").unbind('click')
                var dataTab = arr[i].tab
                var slectDiv = ''
                switch (dataTab) {
                    case '+':
                        slectDiv = '<li class="teststyle testbgclr3EB740" data-tab="+">+</li>'
                        break
                    case '-':
                        slectDiv = '<li class="teststyle testbgclrE96052" data-tab="-">-</li>'
                        break
                    case '+-':
                        slectDiv = '<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>'
                        break
                    case '++':
                        slectDiv = '<li class="teststyle testbgclr177A1A" data-tab="++">++</li>'
                        break
                    case 'N':
                        slectDiv = '<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>'
                        break
                }
                $this.append(slectDiv)
            }
        }
    }

    function showPostion (allPostion, num) {
        var one, two, three, four, five
        for (var i = 0; i < months.length; i++) {
            if (months[i] == num) {
                if (num < 3) {
                    one = months[0]
                    two = months[1]
                    three = months[2]
                    four = months[3]
                    five = months[4]
                } else if (num > 54) {
                    one = months[months.length - 5]
                    two = months[months.length - 4]
                    three = months[months.length - 3]
                    four = months[months.length - 2]
                    five = months[months.length - 1]
                } else {
                    one = months[i - 2]
                    two = months[i - 1]
                    three = months[i]
                    four = months[i + 1]
                    five = months[i + 2]
                }
            }
        }
        var showT = [one, two, three, four, five]
        for (var i = 0; i < showT.length; i++) {
            if (String(showT[i]).indexOf(".") != "-1") {
                var pos = months.indexOf(showT[i])
                showT[i] = weeks[pos] + "周"
            } else {
                showT[i] = showT[i] + "月"
            }
        }
        var title = '<th>能区/智龄</th><th>' + showT[0] + '</th><th>' + showT[1] + '</th><th>' + showT[2] + '</th><th>' + showT[3] + '</th><th>' + showT[4] + '</th>'
        $("#showTitle").html(title)

        var bigMovementTab = '<tr>' + '<td>大运动</td>'
        var fineActionTab = '<tr>' + '<td>精细动作</td>'
        var adaptabilityTab = '<tr>' + '<td>适应能力</td>'
        var languageTab = '<tr>' + '<td>语言</td>'
        var socialBehaviorTab = '<tr>' + '<td>社交行为</td>'

        var arr = new Array(one, two, three, four, five)

        for (var j = 0; j < arr.length; j++) {
            $.each(allPostion, function (index, content) {
                var month = index
                if (month + "" == arr[j] + "") {
                    var params = {
                        month: month,
                        bigMovement: content.bigMovement,
                        fineAction: content.fineAction,
                        adaptability: content.adaptability,
                        language: content.language,
                        socialBehavior: content.socialBehavior
                    }

                    bigMovementTab += '<td>'
                    for (var i = 0; i < params.bigMovement.length; i++) {
                        bigMovementTab += '<div tp="slect" class="td-chd" id="' + params.bigMovement[i].id + '">' + params.bigMovement[i].name + '</div>'
                    }
                    bigMovementTab += '</td>'

                    fineActionTab += '<td>'
                    for (var i = 0; i < params.fineAction.length; i++) {
                        fineActionTab += '<div tp="slect" class="td-chd" id="' + params.fineAction[i].id + '">' + params.fineAction[i].name + '</div>'
                    }
                    fineActionTab += '</td>'

                    adaptabilityTab += '<td>'
                    for (var i = 0; i < params.adaptability.length; i++) {
                        adaptabilityTab += '<div tp="slect" class="td-chd" id="' + params.adaptability[i].id + '">' + params.adaptability[i].name + '</div>'
                    }
                    adaptabilityTab += '</td>'

                    languageTab += '<td>'
                    for (var i = 0; i < params.language.length; i++) {
                        languageTab += '<div tp="slect" class="td-chd" id="' + params.language[i].id + '">' + params.language[i].name + '</div>'
                    }
                    languageTab += '</td>'

                    socialBehaviorTab += '<td>'
                    for (var i = 0; i < params.socialBehavior.length; i++) {
                        socialBehaviorTab += '<div tp="slect" class="td-chd" id="' + params.socialBehavior[i].id + '">' + params.socialBehavior[i].name + '</div>'
                    }
                    socialBehaviorTab += '</td>'
                }
            })
        }
        bigMovementTab += '</tr>'
        fineActionTab += '</tr>'
        adaptabilityTab += '</tr>'
        languageTab += '</tr>'
        socialBehaviorTab += '</tr>'
        $("#showPostion").html(bigMovementTab + fineActionTab + adaptabilityTab + languageTab + socialBehaviorTab)
        setTableStyle(num)
        setResult()
    }

    function setTableStyle (num) {
        //添加点击事件浮层
        if ($("#optionsLayer").length == 0) {
            $(".mainCenter").append('<ul id="optionsLayer" class="btns">' +
                '<li class="bgclr3EB740" data-tab="+">+</li>' +
                '<li class="bgclrE96052" data-tab="-">-</li>' +
                '<li class="bgclr89B9D1" data-tab="+-">+-</li>' +
                '<li class="bgclr177A1A" data-tab="++">++</li>' +
                '<li class="bgclr3AAFA5" data-tab="N">N</li>' +
                '<li class="bgclr999B9B" data-tab="X">X</li>' +
                '</ul>')
        }

        //评估点击事件
        $(".postiontable tr [tp=slect]").click(function () {
            var $this = $(this)
            $this.append($('#optionsLayer').data('slectId', $this.attr('id')).show())
            $this.find(".teststyle").remove()
            var height = $this.height()
            $this.find("li").css({ "height": height / 2 + "px", "line-height": height / 2 + "px" })
        })
        $(".mainCenter").on("click", "li[class*='bgclr']", function () {
            event.stopPropagation()
            var $this = $(this),
                tab = $this.data('tab'), //存储当前li元素data-tab的属性值；
                $slectDiv = $this.closest('.td-chd'),
                $parent = $this.closest('#optionsLayer'),
                slectId = $parent.data('slectId')
            $slectDiv.find('.teststyle').remove()
            switch (tab) {
                case '+':
                    $parent.hide()
                    hashMap.put(slectId, tab)
                    $slectDiv.append('<li class="teststyle testbgclr3EB740" data-tab="+">+</li>')
                    break
                case '-':
                    $parent.hide()
                    hashMap.put(slectId, tab)
                    $slectDiv.append('<li class="teststyle testbgclrE96052" data-tab="-">-</li>')
                    break
                case '+-':
                    $parent.hide()
                    hashMap.put(slectId, tab)
                    $slectDiv.append('<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>')
                    break
                case '++':
                    $parent.hide()
                    hashMap.put(slectId, tab)
                    $slectDiv.append('<li class="teststyle testbgclr177A1A" data-tab="++">++</li>')
                    break
                case 'N':
                    $parent.hide()
                    hashMap.put(slectId, tab)
                    $slectDiv.append('<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>')
                    break
                case 'X':
                    $parent.hide()
                    hashMap.remove(slectId)
                    break
            }
        })

        //切换表格内容重新设置样式
        var index = 4
        if (num == 0.93) index = 2
        if (num == 1.87) index = 3
        if (num == 60) index = 5
        if (num == 72) index = 6
        $(".postiontable tr th:nth-child(" + index + ")").each(function () { //循环table的每行（tr）
            $(this).css({ "background": "#2ab5c7", "color": "#FFF" })
        })
        $(".postiontable tr td:nth-child(" + index + ")").each(function () { //循环table的每行（tr）
            $(this).css({ "background": "#2ab5c7", "color": "#FFF" })
        })

        //添加问题选中样式
        $.each(hashMap.map, function (key, value) {
            if (value == '+') $("#" + key).append('<li class="teststyle testbgclr3EB740" data-tab="+">+</li>')
            if (value == '-') $("#" + key).append('<li class="teststyle testbgclrE96052" data-tab="-">-</li>')
            if (value == '+-') $("#" + key).append('<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>')
            if (value == '++') $("#" + key).append('<li class="teststyle testbgclr177A1A" data-tab="++">++</li>')
            if (value == 'N') $("#" + key).append('<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>')
        })
    }
    //历史记录列表点击：
    $("#dataList").on('click', "ul[result]", function () {
        var data = eval("(" + hashMap.get($(this).attr("result")).replace(/\=/g, "\:") + ")")
        localStorage.setItem("GesellIntelligence", JSON.stringify(data))
        $bb.openPage("gasellIntelligenceResult", obj)
    })
    //历史记录列表：
    function getBabyList (page, rows) {
        $bb.ajax({
            url: URL + "/patient/evaluation/getHistoryScore", //baby地址
            async: false,
            data: JSON.stringify({
                data: {
                    "userId": userId,
                    "examinationPaperName": type,
                    "page": page,
                    "rows": rows
                }
            }),
            success: function (data) {
                if (data.success) {
                    hashMap = new HashMap()
                    count = data.total
                    var babyData = data.rows
                    if (count == 0) {
                        $bb.toastShow("患者还未参与该项测评！")
                    }
                    var str = ''
                    for (var i = 0; i < data.rows.length; i++) {
                        var testDate = data.rows[i].createTime.substring(0, 10)

                        hashMap.put(data.rows[i].answerId, data.rows[i].result)
                        var pretermBirth = 37 * 7 > data.rows[i].pregnancyWeek ? "是" : "否"
                        var nowDate = $common.getNowFormatDate()
                        var monthAge = $common.DateDiff(nowDate, data.rows[i].birthday) / 30
                        var weight = data.rows[i].birthWeight == undefined ? "未知" : data.rows[i].birthWeight + "(g)"
                        var doctorName = data.rows[i].doctorName == undefined ? "未知" : data.rows[i].doctorName

                        str += "<ul class='clearfix' result='" + data.rows[i].answerId + "' >"
                        str += '<li>' + data.rows[i].babyName + '</li>'
                        str += '<li>' + weight + '</li>'
                        str += '<li>' + data.rows[i].birthday + '</li>'
                        str += '<li>' + data.rows[i].pregnancyWeek + '(天)</li>'
                        str += '<li>' + pretermBirth + '</li>'
                        str += '<li>' + doctorName + '</li>'
                        str += '<li>' + data.rows[i].createTime + '</li>'
                        str += '</ul>'
                    }
                    $("#dataList").html(str)
                }
            }
        })
    }

})